<?php
namespace Admin\Controller;
use Admin\Model\UserModel;
use Org\Util\Rbac;
use Think\Controller;
use Org\Util\Image;
use Admin\Model\EmailListModel;
class PublicController  extends  Controller{


    //验证码显示
    public function verify(){
        ob_clean();
        Image::buildImageVerify(4,1,"png",60,26,"verify");
    }
    // 登录检测
    public function checkLogin() {
        if(empty($_POST['account'])) {
            $this->error('帐号错误！');
        }elseif (empty($_POST['password'])){
            $this->error('密码必须！');
        }elseif (empty($_POST['verify'])){
            $this->error('验证码必须！');
        }
        $user_model = new UserModel();
        if ($user_model->hasEmail($_POST['account']) === false){
            $this->error('邮箱不存在');
        }
        $account = explode('@',$_POST['account']);
        $_POST['account'] = $account[0];
        //生成认证条件
        $map            =   array();
        // 支持使用绑定帐号登录
        $map['account']	= $_POST['account'];
        $map["status"]	=	array('gt',0);

        $verify = $_POST['verify'] ;
        if($_SESSION['verify'] != md5($verify)){
            $this->error('验证码输入错误！');
        }

        $authInfo = Rbac::authenticate($map);
        //使用用户名、密码和状态 的方式进行认证
        if(false === $authInfo) {
            $this->error('帐号不存在或已禁用！');
        }else {

            if($authInfo['password'] != md5($_POST['password'])) {
                $this->error('密码错误！');
            }
            if ($_REQUEST['remober']){
                cookie('rember_account',$_POST['account'].'@'.$account[1],time()+3600*24*30);
                cookie('rember_pwd',$_POST['password'],time()+3600*24*30);
            }

//            if ($authInfo['login_count'] == 0){
//                $this->assign('account',$authInfo['account']);
//                $this->display('Public:change_password');
//                return;
//            }

            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
            $_SESSION['account']	=	$authInfo['account'];
            $_SESSION['loginUserName']		=	$authInfo['nickname'];
            $_SESSION['lastLoginTime']		=	$authInfo['last_login_time'];
            $_SESSION['login_count']	=	$authInfo['login_count'];
            if($authInfo['account']=='admin') {
                $_SESSION['administrator']		=	true;
            }
            //保存登录信息
            $User	=	M('User');
            $ip		=	get_client_ip();
            $time	=	time();
            $data = array();
            $data['id']	=	$authInfo['id'];
            $data['last_login_time']	=	$time;
            $data['login_count']	=	array('exp','login_count+1');
            $data['last_login_ip']	=	$ip;
            $User->save($data);

            // 缓存访问权限
            RBAC::saveAccessList();
            $this->success('Loading...',__MODULE__.'/Index/index');

        }
    }

    // 用户登出
    public function logout() {
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION);
            session_destroy();
            $this->success('登出成功！',__CONTROLLER__.'/login/');
        }else {
            $this->error('已经登出！');
        }
    }

    /**
     * 获取读取企业邮件链接
     */
    public function getReadMailUrl() {
        Vendor('exmail.ExmailApi');
        $emailModel = new EmailListModel();
        $emailList = $emailModel->getMailApiListByUserId($_SESSION[C('USER_AUTH_KEY')]);
        $emailobj = $emailList[$_REQUEST['emailkey']-1];

        if($emailobj) {
            $userName = explode('@',$emailobj['email']);
            $userName = $userName[0];
            $exmial =   new \ExmailApi($emailobj['agent'],$emailobj['api_key'],$emailobj['mailbox_suffix']);
        }else {
            $userName = getUserName();
            $exmial =   new \ExmailApi();
        }

        echo $exmial->getReadMaillDetailUrl($userName,$_REQUEST['mailid']);
    }

    /**
     * 修改密码视图
     */
    public function forgotPassword() {

        $res=I('res');
        $user = getLoginUserInfo($_REQUEST['uid']);
        $nowTime = date('Y-m-d',time());

        if( $user['session_key'] == $res && strtotime($user['session_date']) > strtotime($nowTime)  ) {
            $this->display();
        } else {
             $this->error('已经过期',C('DO_MAIN').__APP__);
        }

    }

    /**
     * 改变密码
     */
    public function changePassword() {

        if (empty($_POST['confirmPassword']) || empty($_POST['password'])) {
            $this->error('请输入密码！');
        }
        if ($_POST['confirmPassword'] != $_POST['password']) {
            $this->error('密码输入不一致！');
        }

        $map	=	array();
        $User    =   D("User");
        $map['id']		=	$_POST['id'];

        $User->password	=	pwdHash($_POST['password']);
        if ($User->where($map)->save()!==false){
            $data['session_key'] = '';
            $data['session_date'] = '';
            if (D('User')->where('id='.$_POST['id'])->save($data) === false){
                $this->error('发生内部错误！');
            }
            $this->success('密码修改成功！',C('DO_MAIN').__APP__);
        }else {
            $this->error($User->getLastSql());
        }

    }



    /**
     * 发送修改密码邮件 验证邮箱
     */
    public function viaEmail() {

        $uid = $_REQUEST['uid'];
        $user = getLoginUserInfo($uid);
        if ($_POST['email']) {
            $result = M('User')->where('email="'.trim($_REQUEST['email']).'"')->find();
            if ($result){
                $user = $result;
            } else {
                $this->error('不存在该邮箱！');
            }
        }


        $res = md5(time().rand(1000,2000));
        $data['session_key'] = $res;
        $data['session_date'] = date('Y-m-d',strtotime("+1 day"));
        if (D('User')->where('id='.$user['id'])->save($data) === false){
            $this->error('Session生成失败！');
        }

        $content = explode('.',U('Public/forgotPassword',array('uid' => $user['id'],'res' => $res)));
        $content = '请点击链接，重新输入密码进行修改:'.C('DO_MAIN').$content[0];

        if (sendEmail($user['email'],$user['account'],'ETS One密码找回！',$content,null) ){
			if($_REQUEST['admin']){
				$this->success('发送成功！');
			}else{
				$this->redirect('public/login');
			}
        } else {
            $this->error('发送失败！');
        }
    }

    /**
     *  分享视频
     */
    public function shareVideo() {
        $key = $_REQUEST['key'];
        if ($_REQUEST['share_password']){
            cookie('share_pwd',$_REQUEST['share_password'],3600);
        }
        if (!$key || $key == '') {
            $this->error('链接已经失效',__APP__);
        }

        $data = M('ShareList')->where('var_key="'.$key.'"')->find();

        if (!$data || count($data) < 1){
            $this->error('链接已经失效',__APP__);
        }
        //验证链接的有效时间  暂时有效时间1天
        if (time() - $data['created_at'] > 3600*24){
            $this->error('链接已经失效',__APP__);
        }

        if (!empty($data['share_password'])) {
            $pwd = cookie('share_pwd');
            // 验证密码正确性
            if ($data['share_password'] != $pwd){
                if ($pwd != ''){
                    $this->assign('error','提取码错误');
                }
                $this->assign('key',$key);
                $this->assign('shareder',$data['shareder']);
                $this->display('Public:getShareByPassword');
            }else {

                $this->assign('vo',$data);
                $this->display();
            }

        }else {
            $this->assign('vo',$data);
            $this->display();
        }

    }

    /**
     *  修改初始密码
     */
    public function  changeInitialPassword(){
        if (empty($_REQUEST['account']) || empty($_REQUEST['confirmPassword']) || empty($_REQUEST['password'])){
            $this->error('修改密码失败！');
        }
        $where['account'] = $_REQUEST['account'];
        $model = D('User');

        if ( $_REQUEST['password'] != $_REQUEST['confirmPassword'] ){
            $this->error('确认密码输入有误！');
        }

        $data['password'] = md5($_REQUEST['password']);
        if ($model->where($where)->save($data) === false){
            $this->error('发生内部错误！');
        }

        $authInfo = $model->where($where)->find();
        $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
        $_SESSION['email']	=	$authInfo['email'];
        $_SESSION['loginUserName']		=	$authInfo['nickname'];
        $_SESSION['lastLoginTime']		=	$authInfo['last_login_time'];
        $_SESSION['login_count']	=	$authInfo['login_count'];
        if($authInfo['account']=='admin') {
            $_SESSION['administrator']		=	true;
        }
        //保存登录信息
        $ip		=	get_client_ip();
        $time	=	time();
        $data = array();
        $data['id']	=	$authInfo['id'];
        $data['last_login_time']	=	$time;
        $data['login_count']	=	array('exp','login_count+1');
        $data['last_login_ip']	=	$ip;
        $model->save($data);
        // 缓存访问权限
        RBAC::saveAccessList();
        $this->success('Password changes are successful,now loading...',__MODULE__.'/Index/index');
    }


    public function clearCache() {
    
    	//企业
    	$dep_code = '03';
    	//删除未发货信息
    	S('pending_sales_rmb_total'.$dep_code,null);
    	//删除每个月的完成订单数据
    	for ($i=1;$i<=12;$i++) {
    		S('sales_report_bill_type1_'.$dep_code.'_'.$i,null);
    		S('sales_report_bill_type2_'.$dep_code.'_'.$i,null);
    	}
    	//电商
    	$dep_code = '07';
    	S('pending_sales_rmb_total'.$dep_code,null);
    	for ($i=1;$i<=12;$i++) {
    		S('sales_report_bill_type1_'.$dep_code.'_'.$i,null);
    		S('sales_report_bill_type2_'.$dep_code.'_'.$i,null);
    	}
    }

    /**
     *  login
     */
    public function login() {
        if ($_COOKIE['rember_account'])
            $this->assign('rember_account',$_COOKIE['rember_account']);

        if ($_COOKIE['rember_pwd'])
            $this->assign('rember_pwd',$_COOKIE['rember_pwd']);

        if ($_COOKIE['rember_email'])
            $this->assign('rember_email',$_COOKIE['rember_email']);
        else
            $this->assign('rember_email',1);
        $this->assign('emailSuffix',getEmailSuffix());
       // $this->assign('default_email',1);

        $this->display();
    }

    /**
     * 刷新 首页缓存
     */
    public function refresh() {
        $login_key = getUserName();
        //c6缓存 清空
        S('PendingWorkList'.$login_key,null);
        S('FlatInfoWaitingList'.$login_key,null);
        //邮件缓存
        $emailModel = new EmailListModel();
        $emailList = $emailModel->getMailApiListByUserId($_SESSION[C('USER_AUTH_KEY')]);
        foreach ($emailList as $key => $email) :
        S('MailData'.$key.$login_key,null);
        endforeach;
     //   $this->clearCache();
        $this->success('cache clearing ...',__MODULE__.'/Index/index');
    }

    /**
     *  群发修改密码邮件
     */
    public function sendAllViaEmail() {
        exit;
        $model = D('User');
        $result = $model->field('id,email,account')->where('status=1')->select();
        $count = 0;
        foreach ($result as $u) :
            if ($u['email'] && $u['email'] != 'admin@yuntuservice.com'){
                $res = md5(time().rand(1000,2000));
                $data['session_key'] = $res;
                $data['session_date'] = date('Y-m-d',strtotime("+3 day"));
                if ($model->where('id='.$u['id'])->save($data) === false){
                    echo 'Session生成失败！';die;
                }
                $content = explode('.',U('Public/forgotPassword',array('uid' => $u['id'],'res' => $res)));
                $content = '伙伴们，<br><br> &nbsp;&nbsp; 近期由于出现安全账户被盗事件，为了保障一键登录平台的安全性，烦请大家按以下方式修改一键登录平台的密码，谢谢！
密码输入要求：字母和数字与字符组合并且长度必须大于6，设置链接如下：<br>&nbsp;&nbsp;&nbsp;'.
                    C('DO_MAIN').$content[0].'<br><br> &nbsp;&nbsp; 遇到任何疑问，请直接与IT部人员联系！<br>'.'<br><br>方阵控股 &nbsp;&nbsp;IT部<br>'.date('Y-m-d',time());

                if (sendEmail($u['email'],$u['account'],'"安全提示：请修改一键登录密码',$content,null) === false){
                    echo '发送失败！';
                    die;
                }
                $count++;
            }
        endforeach;
        echo '已经发送了'.$count.' 发送成功！';

    }

    /**
     * 删除个人邮箱条目
     */
    public  function removeMailListItem() {
        $maillist = D('EmailList');
        if($_REQUEST['id'] && $maillist->where('id='.$_REQUEST['id'])->delete() === false){
            $this->error('删除失败： '.$maillist->getDbError());
        }
        $this->success('删除成功！');
    }


}